package com.itheima.algorithm.queue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: TylerZhong
 * @description: 二叉树层序遍历
 */
public class E01Leetcode102 {

    private static class TreeNode {
        private TreeNode left;
        private int val;
        private TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(TreeNode left, int val, TreeNode right) {
            this.left = left;
            this.val = val;
            this.right = right;
        }

        @Override
        public String toString() {
            return String.valueOf(val);
        }
    }
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedListQueue<TreeNode> queue = new LinkedListQueue<>();
        if (root == null) {
            return result;
        }
        queue.offer(root);

        int c1 = 1;
        while (!queue.isEmpty()) {
            int c2 = 0;
            List<Integer> sub = new ArrayList<>();
            for (int i = 0; i < c1; i++) {
                TreeNode poll = queue.poll();
                sub.add(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                    c2++;
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                    c2++;
                }
            }
            result.add(sub);
            System.out.println();
            c1 = c2;
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(
                    new TreeNode(4),
                    2,
                    new TreeNode(5)
                ),
                1,
                new TreeNode(
                        new TreeNode(6),
                        3,
                        new TreeNode(7)
                )
        );
//
//        LinkedListQueue<TreeNode> queue = new LinkedListQueue<>();
//        queue.offer(root);
//
//        int c1 = 1;
//        while (!queue.isEmpty()) {
//            int c2 = 0;
//            for (int i = 0; i < c1; i++) {
//                TreeNode poll = queue.poll();
//                System.out.print(poll+" ");
//                if (poll.left != null) {
//                    queue.offer(poll.left);
//                    c2++;
//                }
//                if (poll.right != null) {
//                    queue.offer(poll.right);
//                    c2++;
//                }
//            }
//            System.out.println();
//            c1 = c2;
//        }

        List<List<Integer>> lists = levelOrder(root);
        System.out.println(lists);
    }
}
